﻿namespace com.crownpack.exporttimer
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;

    using com.crownpack.export;
    using com.crownpack.ExportConfigurationDao;
    using com.crownpack.Extensions.TimeSpanExtensions;
    using com.crownpack.SharePoint;

    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Administration;

    public partial class IncrementalExportJob : SPJobDefinition
    {
        #region Fields

        public const string JOBNAME = "IncrementalExportJob";
        public const string JOBTITLE = " Crown :: Incremental Export as TSV";

        const string JOBDESCRIPTION = "Executes an incremental export of the configured lists as tab-separated values files (*.TSV) to the associated document libraries. For the current configuration, see the site-collection list: Crown Export Configuration. Note: Columns are separated by a horizontal tab (Unicode encoding: 0x0009). Sets of information within a column are separated by a vertical tab (Unicode encoding: 0x000B).";

        #endregion Fields

        #region Constructors

        public IncrementalExportJob( )
            : base()
        {
        }

        public IncrementalExportJob( string name, SPWebApplication webApplication )
            : base(name, webApplication, null, SPJobLockType.Job)
        {
        }

        #endregion Constructors

        #region Properties

        public override string Description
        {
            get
            {
                return JOBDESCRIPTION;
            }
        }

        public override string DisplayName
        {
            get
            {
                return JOBTITLE;
            }
        }

        public string JobTitle
        {
            get
            {
                return JOBNAME;
            }
        }

        #endregion Properties

        #region Methods

        public override void Execute( Guid targetInstanceId )
        {
            Stopwatch overallStopWatch = new Stopwatch( );
            overallStopWatch.Start( );

            try
            {
                CustomLoggingService.LogMessage( JOBNAME, CustomLoggingService.Area.TimerJob, "Timer job {0} :: Started.", JOBNAME );

                SPWebApplication spWebApplication = this.Parent as SPWebApplication;
                if ( spWebApplication == null )
                    throw new Exception( "Web application could not be obtained." );

                List<InvolvedSite> sites = new List<InvolvedSite>( );
                foreach ( SPSite spSite in spWebApplication.Sites )
                {
                    InvolvedSite site = ExportConfigurationDao.GetSiteWithExportConfigurationDefined( spSite.Url );
                    if ( site != null )
                        sites.Add( site );
                }

                foreach ( InvolvedSite site in sites )
                {
                    Stopwatch siteStopWatch = new Stopwatch( );
                    siteStopWatch.Start( );

                    CustomLoggingService.LogMessage( JOBNAME, CustomLoggingService.Area.TimerJob, "Timer job {0} :: Export from {1} started.", JOBNAME, site.SiteUrl );

                    using ( SPSite spSite = new SPSite( site.SiteUrl ) )
                    {
                        using ( SPWeb spWeb = spSite.RootWeb )
                        {
                            IncrementalExportManager o = new IncrementalExportManager( spWeb.Url );
                            bool ok = o.Export( );

                            TimeSpan siteTimeSpan = siteStopWatch.Elapsed;
                            siteStopWatch.Stop( );

                            if ( ok )
                                CustomLoggingService.LogMessage( JOBNAME, CustomLoggingService.Area.TimerJob, "Timer job {0} :: Export from {1} completed normally in {2}.", JOBNAME, site.SiteUrl, siteTimeSpan.FormatAsTotalHoursMinutesSeconds( ) );
                            else
                                CustomLoggingService.LogError( JOBNAME, CustomLoggingService.Area.TimerJob, "Timer job {0} :: Export from {1} ended with errors in {2}. Error exporting 1 or more configured lists from {1}. See warning messages for details.", JOBNAME, spWeb.Url, siteTimeSpan.FormatAsTotalHoursMinutesSeconds( ) );
                        }
                    }
                }

                TimeSpan overallTimeSpan = overallStopWatch.Elapsed;
                overallStopWatch.Stop( );

                CustomLoggingService.LogMessage( JOBNAME, CustomLoggingService.Area.TimerJob, "Timer job {0} :: Completed normally in {1}.", JOBNAME, overallTimeSpan.FormatAsTotalHoursMinutesSeconds( ) );
            }
            catch ( Exception e )
            {
                TimeSpan overallTimeSpan = overallStopWatch.Elapsed;
                overallStopWatch.Stop( );

                CustomLoggingService.LogError( JOBNAME, CustomLoggingService.Area.TimerJob, e, "Timer job {0} :: Ended with errors in {1}.", JOBNAME, overallTimeSpan.FormatAsTotalHoursMinutesSeconds( ) );
            }
        }

        protected override bool HasAdditionalUpdateAccess( )
        {
            return true;
        }

        #endregion Methods
    }
}